package com.xthh.esl;


import android.content.Context;
import android.graphics.Bitmap;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RelativeLayout;


import androidx.exifinterface.media.ExifInterface;

import com.fmsh.compress.CompressUtils;
import com.xt.pro.BLEControlJni;
import com.xt.pro.BleNFCBindInfo;
import com.xthh.XTCore;
import com.xthh._enum.HH_EnumDeviceColorType;
import com.xthh._enum.HH_EnumFileType;
import com.xthh._enum.HH_EnumNfcErrorCode;
import com.xthh._function.HH_CharUtil;
import com.xthh._function.HH_FileUtil;
import com.xthh._function.HH_Logging;
import com.xthh._function.HH_PicUtils;
import com.xthh._function.HH_SystemUtil;
import com.xthh._struct.HH_T_SystemParams;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author wuyajiang
 * @date 2020/5/20
 * 1443-4芯片
 */
public class IsoDepUtils {
    public static final String TAG = "IsoDepUtils";
    private static int sendApdu_back6986_index = 5;
    private static final boolean isLvl = true; // 表示色阶了，我们的程序已经处理图片了，这里默认色阶

    /**
     * 判断是否包含1443-4
     *
     * @param tag
     * @return
     */
    public static boolean isContains(Tag tag) {
        IsoDep isoDep = IsoDep.get(tag);
        if (isoDep == null) {
            return false;
        }
        return true;
    }

    /**
     * 获取AST
     *
     * @param tag
     * @return
     */
    public static byte[] getATS(Tag tag) {
        IsoDep isoDep = IsoDep.get(tag);
        byte[] ast = new byte[2];
        if (isoDep != null) {
            ast = isoDep.getHistoricalBytes();
        }
        return ast;
    }

    public static void startIsoDep(NFCTask nfcTask){
        if (nfcTask == null || nfcTask.getTag() == null){
            return;
        }

        switch (nfcTask.getCommandNFC()){
            case BIND:{
                // bind
                // 先读公司的NDEF数据
                BleNFCBindInfo nfcInfo = ReadNfcData_XT(nfcTask);
                if (nfcInfo != null && nfcInfo.mac != null){
                    HH_Logging.i(TAG, "公司的NFC；%s", nfcInfo.mac);
                    return;
                } else {
                    HH_Logging.i(TAG, "错的信息或不是公司的NFC-1");
                }

                // 获取复旦微信息
                BleNFCBindInfo nfcInfo2 = ReadNfcData_ESL(nfcTask);
                if (nfcInfo2 != null && nfcInfo2.mac != null)
                    HH_Logging.i(TAG, "复旦微的:%s", nfcInfo2.mac);
                else
                    HH_Logging.i(TAG, "错的信息或不是公司的NFC-2");
                break;
            }
            case PIC:{
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.BRUSH.ordinal());
                BrushPic(nfcTask);
                break;
            }
        }
    }
    private static void BrushPic(NFCTask nfcTask){
        IsoDep isoDep = IsoDep.get(nfcTask.getTag());
        if (isoDep != null) {
            try {
                isoDep.setTimeout(50000);
                if (!isoDep.isConnected()) {
                    isoDep.connect();

                    handlerImage(nfcTask.getTpParams().getCtx(), isoDep, nfcTask);
                    //HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), nfcInfo, 0, HH_EnumNfcErrorCode.BIND_INFO.ordinal());

                }
            } catch (Exception e) {
                e.printStackTrace();
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.INCOMPATIBLE_TAG.ordinal());
            } finally {
                try {
                    isoDep.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    private static void handlerImage(Context ctx, IsoDep isoDep, NFCTask nfcTask) throws IOException {

        if (isoDep == null || nfcTask == null || !HH_FileUtil.IsExists(nfcTask.getPath())){
            HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ABNORMAL_PIC_PATH.ordinal());
            return;
        }

        DeviceInfo deviceInfo = IUtils.loadDeviceInfo(ctx, getDeviceInfo(isoDep, ""));

        // 如果与绑定的不同，需要提示
        if (deviceInfo != null){
            HH_Logging.i(TAG, "new = %s,%d,%d,%s", deviceInfo.getUID(), deviceInfo.getWidth(), deviceInfo.getHeight(), deviceInfo.getColor());
            HH_Logging.i(TAG, "bind= %s,%d,%d,%s", nfcTask.getBindInfo().getUID(),
                    nfcTask.getBindInfo().getWidth(),
                    nfcTask.getBindInfo().getHeight(),
                    nfcTask.getBindInfo().getColor());

            if (deviceInfo.getUID() == null){
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ABNORMAL_TAG.ordinal());
                return;
            }
            if (deviceInfo.getColor() == null){
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ABNORMAL_COLOR.ordinal());
                return;
            }

            if (!HH_CharUtil.Strcmp(deviceInfo.getUID(), nfcTask.getBindInfo().getUID(), true)){
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ABNORMAL_PARAMS.ordinal());
                return;
            }

            // 下面的就不用了，因为颜色不同不好判断
            /*if (deviceInfo.getWidth() != nfcTask.getBindInfo().getWidth() ||
                    deviceInfo.getHeight() != nfcTask.getBindInfo().getHeight() ||
                    !HH_CharUtil.Strcmp(deviceInfo.getColor(), nfcTask.getBindInfo().getColor(), true)){
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ABNORMAL_PARAMS.ordinal());
                return;
            }*/


            HH_Logging.i(TAG, "here_001:%s,%s", deviceInfo.getColor(), nfcTask.getBindInfo().getColor());



            // 复旦微图片
            // 转成黑白图
            if (HH_CharUtil.Strcmp(nfcTask.getBindInfo().getColor(), "BW", true)){

                Bitmap b2 = BmpUtils.convertToBlackWhite(HH_PicUtils.GetBitmapFormFile(nfcTask.getPath()));
                String tempP = HH_SystemUtil.GetTempPath(nfcTask.getTpParams(), 0, HH_EnumFileType.BMP);
                BmpUtils.saveBmp(b2, tempP);
                BmpUtils.Convert24bmpToBlackWithebmp(tempP, nfcTask.getPath(), true, nfcTask, deviceInfo);
            }

            boolean bmpFormat = BmpUtils.GetBmpFormat(nfcTask, deviceInfo);
            int color_cnt = deviceInfo.getColorCount();
            HH_Logging.i(TAG, "here_002-%b,%d", bmpFormat, color_cnt);
            if (bmpFormat) {
                if (color_cnt == 2) {
                    writeBlackWhiteScreen(isoDep, nfcTask, deviceInfo);
                } else if (color_cnt == 3) {
                    //write3ColorScreen(isoDep, isLvl, nfcTask, deviceInfo;
                } else {
                    if ((color_cnt == 4) && (null != deviceInfo.getColorDesc())) {
                        write4ColorScreen(isoDep, isLvl, deviceInfo, nfcTask);
                    } else {
                        //writeMulColorScreen(isoDep, isLvl, nfcTask, deviceInfo);
                    }
                }
            } else {
                //UIUtils.sendMessage(UIUtils.getString(R.string.bmp_error), -1, App.getHandler());
            }

            /*int deviceType = HH_SystemUtil.GetEslDeviceTypeFormColor(deviceInfo.getColor());




            if (HH_CharUtil.Strcmp(nfcTask.getBindInfo().getColor(), "BW", true)){

                writeBlackWhiteScreen(isoDep, nfcTask, deviceInfo);

            } else if (HH_CharUtil.Strcmp(nfcTask.getBindInfo().getColor(), "BWR", true)){
                //write3ColorScreen(isoDep);
            } else if (HH_CharUtil.Strcmp(nfcTask.getBindInfo().getColor(), "BWRY", true)){
                //write4ColorScreen(isoDep);
            }*/

        } else {
            HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ABNORMAL_DATA.ordinal());
            return;
        }


        return;
        /*boolean bmpFormat = BmpUtils.GetBmpFormat(mBmpPath, deviceInfo);
        if (bmpFormat) {
            int color_cnt = deviceInfo.getColorCount();
            if (color_cnt == 2) {
                writeBlackWhiteScreen(isoDep);
            } else if (color_cnt == 3) {
                write3ColorScreen(isoDep, isLvl);
            } else {
                if ((color_cnt == 4) && (null != deviceInfo.getColorDesc())) {
                    write4ColorScreen(isoDep, isLvl);
                } else {
                    writeMulColorScreen(isoDep, isLvl);
                }
            }
        } else {
            UIUtils.sendMessage(UIUtils.getString(R.string.bmp_error), -1, App.getHandler());
        }*/
    }

    static BleNFCBindInfo ReadNfcData_ESL(NFCTask taskInfo){
        BleNFCBindInfo nfcInfo = new BleNFCBindInfo();
        IsoDep isoDep = IsoDep.get(taskInfo.getTag());
        if (isoDep != null) {
            try {
                isoDep.setTimeout(50000);
                if (!isoDep.isConnected()) {
                    isoDep.connect();
                    String hexInfo = getDeviceInfo(isoDep, "");

                    DeviceInfo di = IUtils.loadDeviceInfo2(hexInfo);

                    nfcInfo.mac = di.getUID();
                    nfcInfo.deviceWidth = di.getWidth();
                    nfcInfo.deviceHeight = di.getHeight();
                    nfcInfo.deviceColor = di.getColor();
                    // 用这个来存详细数据，在刷图时要到到
                    nfcInfo.customSRRC = hexInfo;
                    nfcInfo.deviceNumber = XTCore.DEVICE_NUMBER_ESL;

                    HH_SystemUtil.SendMessage(taskInfo.getTpParams(), taskInfo.getMsg(), nfcInfo, 0, HH_EnumNfcErrorCode.BIND_INFO.ordinal());

                }
            } catch (Exception e) {
                e.printStackTrace();
                HH_SystemUtil.SendMessage(taskInfo.getTpParams(), taskInfo.getMsg(), "", 0, HH_EnumNfcErrorCode.INCOMPATIBLE_TAG.ordinal());
            } finally {
                try {
                    isoDep.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return nfcInfo;
    }



    /**
     * 获取设备信息
     *
     * @param isoDep
     * @throws IOException
     */
    private static String getDeviceInfo(IsoDep isoDep, String pin) throws IOException {

        //开始FMSC对外供电
        byte[] result3 = isoDep.transceive(FMUtil.hexToByte("F0D801FE050000000000"));
        //获取配置信息
        byte[] result = isoDep.transceive(FMUtil.hexToByte("00D1000000"));
        //检测是否支持pin
        byte[] result2 = isoDep.transceive(FMUtil.hexToByte("F0D8000005000000000E"));

        //DeviceInfo deviceInfo = IUtils.loadDeviceInfo(FMUtil.byteToHex(result) + FMUtil.byteToHex(result2));

        return FMUtil.byteToHex(result) + FMUtil.byteToHex(result2);
    }

    static BleNFCBindInfo ReadNfcData_XT(NFCTask taskInfo){
        BleNFCBindInfo nfcInfo = null;
        //String sMac = null;
        Ndef isoDep = Ndef.get(taskInfo.getTag());
        if (isoDep != null) {
            try {
                if (!isoDep.isConnected()) {
                    isoDep.connect();
                }

                NdefMessage ndefReadMessage = null;
                try {
                    ndefReadMessage = isoDep.getNdefMessage();
                } catch (FormatException e) {

                } catch (IOException e) {

                }
                if (ndefReadMessage != null) {
                    NdefRecord nrArray[] = ndefReadMessage.getRecords();
                    String sReadAll = "";
                    for (int i = 0; i < nrArray.length; i++) {
                        NdefRecord record = nrArray[i];

                        byte bRecvOrder[] = HH_SystemUtil.parseTextRecord(record);
                        sReadAll = new String(bRecvOrder);
                        if (sReadAll != null && sReadAll.length() > 0)
                            break;
                    }

                    byte []bNfcInfo = HH_CharUtil.StringToByte2(sReadAll, "GB2312");
                    nfcInfo = BLEControlJni.GetBleNFCBindInfo(bNfcInfo, bNfcInfo.length);

                    if (nfcInfo != null && nfcInfo.mac.length() == 12){
                        if (nfcInfo.customSN == null)
                            nfcInfo.customSN = "";
                        if (nfcInfo.customSRRC == null)
                            nfcInfo.customSRRC = "";
                        if (nfcInfo.customerCode == null)
                            nfcInfo.customerCode = "";
                        // 返回绑定成功
                        //sMac = nfcInfo.mac;
                        HH_SystemUtil.SendMessage(taskInfo.getTpParams(), taskInfo.getMsg(), nfcInfo, 0, HH_EnumNfcErrorCode.BIND_INFO.ordinal());
                    } else {
                        HH_SystemUtil.SendMessage(taskInfo.getTpParams(), taskInfo.getMsg(), "", 0, HH_EnumNfcErrorCode.ABNORMAL_DATA.ordinal());
                    }
                }
            } catch (Exception e) {
                HH_SystemUtil.SendMessage(taskInfo.getTpParams(), taskInfo.getMsg(), "", 0, HH_EnumNfcErrorCode.INCOMPATIBLE_TAG.ordinal());
            } finally {
                try {
                    isoDep.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return nfcInfo;
    }


    /**
     * 黑白图片刷屏
     *
     * @param isoDep
     */
    /*private static void writeBlackWhiteScreen(IsoDep isoDep, NFCTask nfcTask, DeviceInfo deviceInfo1) {
        //LogUtil.d("开始", System.currentTimeMillis());
        byte[] bmpdata = ImageUtils.ReadBmp8File(nfcTask.getPath(), deviceInfo.getWidth(), deviceInfo.getHeight());
        if (bmpdata == null) {
            return;
        }
        //LogUtil.d("结束", System.currentTimeMillis());
//        LogUtil.d(FMUtil.byteToHex(bmpdata));

        int destRealWidth = (int) Math.ceil(deviceInfo.getWidth() / 8.0);
        int destWidth = 0;
        int percent = destRealWidth % 4;
        if (percent != 0) {
            destWidth += destRealWidth - percent + 4;
        } else {
            destWidth = destRealWidth;
        }
        int vbitsRow = (int) Math.ceil(deviceInfo.getHeight() / 8.0);

        byte[] result = new byte[bmpdata.length];
        if (deviceInfo.getRefreshScan() == 0) {
            ImageUtils.VerticalScanning(result, bmpdata, destRealWidth, vbitsRow, destWidth);
        } else {
            result = ImageUtils.HorizontalScanning(bmpdata, destRealWidth, deviceInfo.getHeight(), destWidth);
        }
        // 行数等于总的字节数 / 每次发送的字节数250 / 8 向上取整
        int rowCount = (int) Math.ceil(deviceInfo.getWidth() * deviceInfo.getHeight() / 250 / 8.0);
        if (!WriteBmpdataEx(isoDep, result, rowCount, 0)) {
            return;
        }
        RefreshScreenAfterWriteBmpdataex(isoDep, 0);
    }*/


    /**
     * 黑白图片刷屏
     *
     * @param isoDep
     */
    private static void writeBlackWhiteScreen(IsoDep isoDep, NFCTask nfcTask, DeviceInfo deviceInfo) {

        HH_Logging.i(TAG, "writeBlackWhiteScreen;%d,%d,%s", deviceInfo.getWidth(), deviceInfo.getHeight(), nfcTask.getPath());
        byte[] bmpdata = ImageUtils.ReadBmp8File(nfcTask.getPath(), deviceInfo.getWidth(), deviceInfo.getHeight());
        if (bmpdata == null) {
            HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
            return;
        }

//        LogUtil.d(FMUtil.byteToHex(bmpdata));

        int destRealWidth = (int) Math.ceil(deviceInfo.getWidth() / 8.0);
        int destWidth = 0;
        int percent = destRealWidth % 4;
        if (percent != 0) {
            destWidth += destRealWidth - percent + 4;
        } else {
            destWidth = destRealWidth;
        }
        int vbitsRow = (int) Math.ceil(deviceInfo.getHeight() / 8.0);

        byte[] result = new byte[bmpdata.length];
        if (deviceInfo.getRefreshScan() == 0) {
            ImageUtils.VerticalScanning(result, bmpdata, destRealWidth, vbitsRow, destWidth);
        } else {
            result = ImageUtils.HorizontalScanning(bmpdata, destRealWidth, deviceInfo.getHeight(), destWidth);
        }
        // 行数等于总的字节数 / 每次发送的字节数250 / 8 向上取整
        int rowCount = (int) Math.ceil(deviceInfo.getWidth() * deviceInfo.getHeight() / 250 / 8.0);
        if (!WriteBmpdataEx(isoDep, result, rowCount, 0, deviceInfo, nfcTask)) {
            return;
        }
        RefreshScreenAfterWriteBmpdataex(isoDep, 0, deviceInfo, nfcTask);
    }


    /**
     * @param result
     * @param rowCount
     * @return
     */
    private static boolean WriteBmpdataEx(IsoDep isoDep, byte[] result, int rowCount, int ScreenIndex, DeviceInfo deviceInfo, NFCTask nfcTask) {
        boolean isCompress = deviceInfo.isCompress();
        //boolean isCompress =false;
        int m_bmpWidth = deviceInfo.getWidth();
        int m_bmpHeight = deviceInfo.getHeight();
        int size = 0;
        if (isCompress) {
            try {
                //LogUtil.d("压缩", System.currentTimeMillis());
                //LogUtil.d(FMUtil.byteToHex(result));
                int divider = 8;

                String ColorDesc = deviceInfo.getColorDesc();
                if (null == ColorDesc) {
                    divider = 8;
                } else if (deviceInfo.getColor().contentEquals("黑白红黄四色")) {
                    divider = 4; // 四色 2字节 一个像素 4的 倍数
                }

                if (deviceInfo.getRefreshScan() == 0) {
                    int p = m_bmpHeight % divider;
                    if (p != 0) {
                        m_bmpHeight = (divider - p) + m_bmpHeight;
                    }
                }else {
                    int p = m_bmpWidth % divider;
                    if (p != 0) {
                        m_bmpWidth = (divider - p) + m_bmpWidth;
                    }
                }
                size = m_bmpWidth * m_bmpHeight / divider;

//                                if(deviceInfo.getColorCount() == 2){
//                                   int width =  (int) Math.ceil(m_bmpWidth / 8.0);
//                                     size = width * m_bmpHeight /8;
//                                }
                byte[] bytes = new byte[size];
                System.arraycopy(result, 0, bytes, 0, bytes.length);
                result = bytes;
                //LogUtil.d(FMUtil.byteToHex(result));
                //LogUtil.d("压缩开始", System.currentTimeMillis());
                String compress = CompressUtils.compress(isoDep, result, ScreenIndex);
                //LogUtil.d("压缩完成", System.currentTimeMillis());
                if ("9000".equals(compress)) {
                    return true;
                } else {
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                return false;
            }

        } else {
            //LogUtil.d("发送", System.currentTimeMillis());
            if (result.length < rowCount * 0xFA) {
                byte[] temp = new byte[rowCount * 0xFA];
                System.arraycopy(result, 0, temp, 0, result.length);
                result = temp;
            }
            byte[] apdu = new byte[0xFA + 5];
            apdu[0] = (byte) 0xF0;
            apdu[1] = (byte) 0xD2;
            apdu[2] = (byte) ScreenIndex;
            apdu[4] = (byte) 0xFA;
            for (int i = 0; i < rowCount; i++) {
                // 索引号
                apdu[3] = (byte) i;
                for (int j = 0; j < 0xFA; j++) {
                    apdu[5 + j] = (byte) result[i * 0xFA + j];
                }
                try {
//                    LogUtil.d(FMUtil.byteToHex(apdu));
                    byte[] datasw = isoDep.transceive(apdu);

                    String strResponse = FMUtil.byteToHex(datasw);
                    if (!strResponse.substring(strResponse.length() - 4).equals("9000")) {
                        HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                        return false;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    return false;
                }
            }
        }
        return true;
    }


    private static void RefreshScreenAfterWriteBmpdataex(IsoDep isoDep, int ScreenIndex, DeviceInfo deviceInfo, NFCTask nfcTask) {
        //LogUtil.d("刷屏", System.currentTimeMillis());
        byte[] refreshcmd = new byte[0x5];
        refreshcmd[0] = (byte) 0xF0;
        refreshcmd[1] = (byte) 0xd4;
        refreshcmd[2] = (byte) 0x85;
        refreshcmd[3] = (byte) (ScreenIndex | (byte) 0x80);
        refreshcmd[4] = (byte) 0x00;
        try {
            //LogUtil.d(FMUtil.byteToHex(refreshcmd));
            byte[] datasw = isoDep.transceive(refreshcmd);
            String strResponse = FMUtil.byteToHex(datasw);
            //LogUtil.d(strResponse);

            if (strResponse.equals("698A")) {
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
            } else if (strResponse.equals("6986") || "68C6".equals(strResponse)) {
                if (sendApdu_back6986_index > 0) {
                    sendApdu_back6986_index--;
                    //RefreshScreenAfterWriteBmpdataex(isoDep, ScreenIndex);
                    datasw = isoDep.transceive(FMUtil.hexToByte("F0D4850000"));

                    strResponse = FMUtil.byteToHex(datasw);
                    //LogUtil.d(strResponse);
                    if (strResponse.equals("009000") || strResponse.equals("9000") || strResponse.equals("019000")) {
                        sendApdu_back6986_index = 5;
                        //IUtils.sendMessage(ActivityUtils.instance.getCurrentActivity().getResources().getString(R.string.text_success), 0);
                        HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ESL_SUCCESS.ordinal());
                    } else {
                        //IUtils.sendMessage("Error:" + strResponse, -1);
                        HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), strResponse, 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    }
                } else {
                    //String strtmp = ActivityUtils.instance.getCurrentActivity().getResources().getString(R.string.string_res_37);
                    //IUtils.sendMessage(strtmp, -1);
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "屏幕接入异常，请排查后重新尝试", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    sendApdu_back6986_index = 5;
                }


            } else if (strResponse.equals("019000")) {
                //有源
                sendApdu_back6986_index = 5;
                HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ESL_SUCCESS.ordinal());
            } else if (strResponse.equals("009000") || strResponse.equals("9000")) {
                //无源
                sendApdu_back6986_index = 5;
                GetRefreshResult(isoDep, ScreenIndex, deviceInfo, nfcTask);
            } else {
                refreshcmd[3] = (byte) ScreenIndex;
                datasw = isoDep.transceive(refreshcmd);
                strResponse = FMUtil.byteToHex(datasw);
                if (!strResponse.equals("9000")) {
                    // RevEdit.setText("刷屏时发生错误，错误码:" + strResponse);
                    //String strtmp = ActivityUtils.instance.getCurrentActivity().getResources().getString(R.string.string_res_16);
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "刷屏时发生错误，错误码:" + strResponse, 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                } else {
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ESL_SUCCESS.ordinal());
                }
            }
            //LogUtil.d("刷屏", System.currentTimeMillis());
        } catch (IOException e) {
            e.printStackTrace();
            HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
        }

    }


    private static void GetRefreshResult(IsoDep isoDep, int ScreenIndex, DeviceInfo deviceInfo, NFCTask nfcTask) {
        byte[] refreshcmd = new byte[0x5];
        refreshcmd[0] = (byte) 0xF0;
        refreshcmd[1] = (byte) 0xd4;
        refreshcmd[2] = (byte) 0x05;
        refreshcmd[3] = (byte) (ScreenIndex | (byte) 0x80);
        refreshcmd[4] = (byte) 0x00;
        String m_strLastErrorMsg = "Error";
        try {
            byte[] datasw = null;
            String strResponse;
            //循环去取刷屏幕的结果
            refreshcmd[1] = (byte) 0xde;
            refreshcmd[2] = (byte) 0x0;
            refreshcmd[3] = (byte) (0x0);
            refreshcmd[4] = (byte) 0x01;


            for (int i = 0; i < 1000; i++) {
//                LogUtil.d(FMUtil.byteToHex(refreshcmd));
                datasw = isoDep.transceive(refreshcmd);
                strResponse = FMUtil.byteToHex(datasw);
                Log.d("<-", strResponse);
                if (strResponse.equals("009000")) {
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "", 0, HH_EnumNfcErrorCode.ESL_SUCCESS.ordinal());
                    //IUtils.sendMessage(ActivityUtils.instance.getCurrentActivity().getResources().getString(R.string.text_success), 0);
                    //LogUtil.d("success", System.currentTimeMillis());
                    return;
                } else if (strResponse.equals("019000")) {
                    Thread.sleep(100); //还需要等待
                } else if (strResponse.equals("698A")) {
                    String strtmp = "请移动设备以找到合适的NFC接触区域:";
                    m_strLastErrorMsg = strtmp + strResponse;
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    //IUtils.sendMessage(m_strLastErrorMsg, -1);
                    return;
                } else if (strResponse.equals("6986") || "68C6".equals(strResponse)) {
                    //String strtmp = ActivityUtils.instance.getCurrentActivity().getResources().getString(R.string.string_res_37);
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "屏幕接入异常，请排查后重新尝试", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    //IUtils.sendMessage(strtmp, -1);
                    return;
                } else {

                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "屏幕接入异常，请排查后重新尝试" + strResponse, 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    //String strtmp = ActivityUtils.instance.getCurrentActivity().getResources().getString(R.string.hint_error);
                    //m_strLastErrorMsg = strtmp + strResponse;
                    //IUtils.sendMessage(strtmp, -1);
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //IUtils.sendMessage(UIUtils.getString(R.string.hint_error), -1);
            HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
        }
    }



    private static void write4ColorScreen(IsoDep isoDep, boolean isLvl, DeviceInfo deviceInfo, NFCTask nfcTask) {
        HH_Logging.i(TAG, "write4ColorScreen:%s", nfcTask.getPath());
        deviceInfo.setBitmap(HH_PicUtils.GetBitmapFormFile(nfcTask.getPath()));
        byte[] bmpdata = ImageUtils.ReadBmp24File(nfcTask.getPath(), isLvl, deviceInfo, nfcTask);
        if (bmpdata == null) {
            HH_Logging.i(TAG, "write4ColorScreen fail");
            HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
            return;
        }
        int width = deviceInfo.getWidth();
        int height = deviceInfo.getHeight();
        byte[] data1 = new byte[width * height];
        byte[] data2 = new byte[width * height];
        HH_Logging.i(TAG, "write4ColorScreen wh=%d*%d", width, height);

        ImageUtils.getColorDataBmp4(bmpdata, data1, deviceInfo, nfcTask);

        byte[] result = null;
        byte[] result1 = null;
        String ColorDesc = deviceInfo.getColorDesc();
        if (null == ColorDesc) {
            if (deviceInfo.getRefreshScan() == 0) {
                result = ImageUtils.Color24VerticalScanning(data1, deviceInfo, nfcTask);
                result1 = ImageUtils.Color24VerticalScanning(data2, deviceInfo, nfcTask);
            } else {
                result = ImageUtils.color24horizontalScanning(data1, deviceInfo, nfcTask);
                result1 = ImageUtils.color24horizontalScanning(data2, deviceInfo, nfcTask);
            }
        } else if (deviceInfo.getColor().contentEquals("黑白红黄四色")) {

            if (deviceInfo.getRefreshScan() == 0) {
                result = ImageUtils.Color4VerticalScanning(data1, deviceInfo, nfcTask);
            } else {
                result = ImageUtils.color4horizontalScanning(data1, deviceInfo, nfcTask);
            }

        }
        // 行数等于总的字节数 / 每次发送的字节数250 / 8 向上取整
        int rowCount = (int) Math.ceil(width * height / 250 / 8.0);

        HH_Logging.i(TAG, "write4ColorScreen rowCount=%d", rowCount);

        if (null == ColorDesc) {
            if (deviceInfo.getSize() == 1) {
                if (!WriteBmpdataEx(isoDep, result, rowCount, 0, deviceInfo, nfcTask)) {
                    HH_Logging.i(TAG, "write4ColorScreen fail-0");
                    return;
                }

            } else if (deviceInfo.getSize() == 2) {
                if (!WriteBmpdataEx(isoDep, result, rowCount, 0, deviceInfo, nfcTask)) {
                    HH_Logging.i(TAG, "write4ColorScreen fail-1");
                    return;
                }
                if (!WriteBmpdataEx(isoDep, result1, rowCount, 1, deviceInfo, nfcTask)) {
                    HH_Logging.i(TAG, "write4ColorScreen fail-2");
                    return;
                }

            }
        } else if (deviceInfo.getColor().contentEquals("黑白红黄四色")) {
            if (deviceInfo.getSpecialScreen().equals("SE0398N01_02")) {
                // TODO: 2024/10/23  按照规定转换数据
                if (result == null) {
                    HH_Logging.i(TAG, "write4ColorScreen fail-3");
                    //UIUtils.sendMessage("Error", -1, App.getHandler());
                    HH_SystemUtil.SendMessage(nfcTask.getTpParams(), nfcTask.getMsg(), "请移动设备以找到合适的NFC接触区域", 0, HH_EnumNfcErrorCode.ESL_HINT_ERROR.ordinal());
                    return;
                }
                if (width == 552 && height == 768) {
                    byte[] d = new byte[768 * 552 / 4];
                    result = SE0398N.swap_pic_n01(d, result);
                }
            }
            if (!WriteBmpdataEx(isoDep, result, rowCount * 2, 0, deviceInfo, nfcTask)) {
                HH_Logging.i(TAG, "write4ColorScreen fail-4");
                return;
            }
        }
        RefreshScreenAfterWriteBmpdataex(isoDep, 0, deviceInfo, nfcTask);
    }
}

